package com.example.internetplus.websocket;

import cn.hutool.json.JSONUtil;
import com.example.internetplus.config.WebSocketConfig;
import com.example.internetplus.controller.globalException.exception.SystemException;
import com.example.internetplus.domain.po.User;
import com.example.internetplus.utils.RedisUtil;
import com.example.internetplus.utils.UserContext;
import com.example.internetplus.websocket.pojo.SystemMessage;
import com.example.internetplus.websocket.pojo.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springfox.documentation.annotations.Cacheable;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat", configurator = WebSocketConfig.class)
@Component
public class ChatEndpoint {
    private Long userId = UserContext.getUser();
    private Long toUserId = null;
    private String cacheKey = "user:chat:" + userId + "to:" +  toUserId;
    private final static Map<Long,Session> onlineUsers = new ConcurrentHashMap<>();
    @Autowired
    private RedisUtil redisUtil;
    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        //保存session
        onlineUsers.put(userId,session);
        Set<Long> onFriends = getFriends();
        //广播，将登录消息广播
        SystemMessage message = new SystemMessage(onFriends.toString());
        broadcastAllUser(message);
    }
    //广播
    private void broadcastAllUser(SystemMessage message){
        Set<Map.Entry<Long, Session>> entries = onlineUsers.entrySet();
        for (Map.Entry<Long, Session> entry : entries) {
            Session session = entry.getValue();
            //异步消息
            //session.getAsyncRemote()
            try {
                session.getBasicRemote().sendText(message.getMessage());
            } catch (IOException e) {
                throw new SystemException("发送消息异常",10503);
            }
        }
    }

    private Set<Long> getFriends(){
        return onlineUsers.keySet();
    }
    @OnMessage
    public void onMessage(String message){
        //message是json数据；
        UserMessage userMessage = JSONUtil.toBean(message, UserMessage.class);
        toUserId = userMessage.getToUser();
        userMessage.setToUser(null);
        Session session = onlineUsers.get(toUserId);
        redisUtil.addList(cacheKey,message);
        try {
            session.getBasicRemote().sendText(userMessage.toString());
        } catch (IOException e) {
            throw new SystemException("获取session失败",10503);
        }

    }
    @OnClose
    public void onCloes(Session session){
        Long user = UserContext.getUser();
        onlineUsers.remove(user);
        try {
            session.close();
        } catch (IOException e) {
            throw new SystemException("关闭session失败",10503);
        }
    }
}

